import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select, TreeSelect, Popover, Tooltip,
} from 'antd';

import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import PaperInvoicing from './PaperInvoicing'
import BuildModalTitle from '@/components/BuildModalTitle';

import Highlighter from 'react-highlight-words';
import debounce from 'lodash/debounce';
import {
  popoverPrice,
  printUtils,
  renderTreeNodes,
  download,
  formateObjToParamStr,
  printUtilsLevel,
  afterCloseModal
} from '@/utils/utils';
import Detail from './../Owner/Detail';
import ReactDataGrid from 'react-data-grid';
import gold from './../../images/gold.png';
import wechat from './../../images/wechat.png';
import request from '@/utils/request';
import config from '../../config/config';
import find from 'lodash/find';

const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;
const InputGroup = Input.Group;

@connect(({ payment, loading, global }) => ({
  payment,
  global,
  loading: loading.models.payment,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      data: [],
      remark:'',
      price_nature:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      payment: { pageLoaded, scrollData },
    } = this.props;

    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        payment: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'payment/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'payment/changeLoaded',
          });
          dispatch({
            type: 'payment/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }
    });
    request(`/all_price_natures`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          price_nature: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    // document.addEventListener('keyup', this.keyupFunc);

  }

  keyupFunc = (e) => {
    if (e.keyCode === 13) {
      this.searchFunc();
    }
  };
  searchFunc = () => {
    const that = this;
    const { form, payment: { searchParams } } = that.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.handleSearch({
        page: 1,
        per_page: searchParams.per_page,
        ...fieldsValue,
        start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
        end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
        region_id: fieldsValue.region_id ? fieldsValue.region_id.split('$')[0] : '',
        region_name: fieldsValue.region_id ? fieldsValue.region_id.split('$')[1] : '',

      });

    });
  };
  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'payment/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'payment/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    // document.removeEventListener('keyup', this.keyupFunc);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  findChildFunc = (cb) => {
    this.findChildLocation = cb;
  };
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    const {
      payment: { searchInputType, searchInputText },
    } = this.props;
    dispatch({
      type: 'payment/fetch',
      payload: {
        ...values,
        [searchInputType]: searchInputText,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const data = this.state.data;
    const { dispatch } = this.props;
    const {
      form: { getFieldDecorator },
      payment: { searchParams, searchInputType, searchInputText },
    } = this.props;
    let branch_id=sessionStorage.getItem('branch_id');
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>

        <FormItem label="区域">
          {getFieldDecorator('region_id', {
            initialValue: searchParams.region_id ? `${searchParams.region_id}$${searchParams.region_name}` : '',
          })(
            <TreeSelect
              style={{ width: '110px' }}
              allowClear
              treeDefaultExpandAll={Boolean(branch_id)}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              showSearch
            >
              {renderTreeNodes(data)}
            </TreeSelect>,
          )}
        </FormItem>
        <FormItem label="类型">
          {getFieldDecorator('type', {
            initialValue: searchParams.type,
          })(
            <Select style={{ width: '100px' }}>
              {
                [{ id: '', value: '全部' },
                  { id: '1', value: '现金' },
                  { id: '2', value: '支票' },
                  { id: '3', value: '银行卡' },
                  { id: '4', value: '微信扫码' },
                  { id: '5', value: '支付宝扫码' },
                  { id: '6', value: '网银' },
                  { id: '30', value: '补水' },
                  { id: '31', value: '换表补水' },
                  { id: '11', value: '公众号缴费' },
                  { id: '12', value: '公众号建行' },
                  { id: '13', value: '建行APP缴费' },
                  {
                  id: '20',
                  value: '撤销缴费',
                }].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.value}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="开票状态">
          {getFieldDecorator('invoicing_status', {
            initialValue: searchParams.invoicing_status,
          })(
            <Select style={{ width: '100px' }}>
              {
                [{ id: '', value: '全部' }, { id: '-3', value: '开票失败' }, { id: '-2', value: '不允许开票' },
                  {id: '-1', value: '未开票'}, {id: '1', value: '正在开票'}, {id: '2', value: '已开票'}
                  ].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.value}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem
          label={'用水性质'}
        >
          {getFieldDecorator(`price_nature_id`, {
            initialValue:  searchParams.price_nature_id,

          })(
            <Select  style={{width:'140px'}} dropdownMatchSelectWidth={false}>
              <Option value={''}>
                全部
              </Option>
              {
                this.state.price_nature.map((item,index)=>{
                  return <Option title={item.name} key={index} value={item.id}>
                    <Highlighter
                      highlightClassName="YourHighlightClass"
                      searchWords={["有下水"]}
                      highlightStyle={{backgroundColor:'#fdffd0',padding:'0'}}
                      autoEscape={true}
                      textToHighlight= {item.name}
                    /></Option>
                })
              }
            </Select>
          )}
        </FormItem>
        <FormItem>
          <InputGroup compact>
            <Select onChange={(e) => {
              dispatch({
                type: 'payment/changeOneProperty',
                payload: {
                  searchInputType: e,
                },
              });
            }} style={{ width: '100px', color: '#000' }} value={searchInputType}>
              <Option value="mobile">户主手机</Option>
              <Option value="name">户主姓名</Option>
              <Option value="meter_number">水表号</Option>
              <Option value="operator_name">操作员</Option>
            </Select>
            <Input style={{ width: '130px' }} value={searchInputText}  onKeyPress={this.keyPress} onChange={(e) => {
              dispatch({
                type: 'payment/changeOneProperty',
                payload: {
                  searchInputText: e.target.value,
                },
              });
            }}/>
          </InputGroup>
        </FormItem>
        {/* <FormItem label="操作员">
          {getFieldDecorator('operator_name', {
            initialValue: searchParams.operator_name,
          })(<Input style={{ width: '110px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="户主姓名">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{ width: '120px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="户主手机">
          {getFieldDecorator('mobile', {
            initialValue: searchParams.mobile,
          })(<Input style={{ width: '120px' }} placeholder="请输入"/>)}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '110px' }} placeholder="请输入"/>)}
        </FormItem>*/}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              this.searchFunc();
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        this.searchFunc()
      });
    }
  }
  handleAdd = () => {
    const location = this.findChildLocation();
    console.log('location', location);
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'payment/add',
      payload: {
        ...formValues,
        longitude: location[0],
        latitude: location[1],
      },
      callback() {
        message.success('添加压力传感器成功');
        that.setState({
          addModal: false,
        });
        const {
          payment: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    const { dispatch } = this.props;
    const that=this
    form.resetFields();
    dispatch({
      type: 'payment/changeOneProperty',
      payload: {
        searchInputType: 'mobile',
        searchInputText: '',
        searchParams: {
          start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
          end_date:moment(new Date()).format('YYYY-MM-DD'),
          region_id:"",
          name:'',
          mobile:'',
          meter_number:'',
          type: '',
          invoicing_status:'',
          price_nature_id:'',
          page: 1,
          per_page: 50,
        },
      },
      callback() {
        that.handleSearch({
          start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD').format('YYYY-MM-DD'),
          end_date: moment(new Date()).format('YYYY-MM-DD'),
          region_id: '',
          name: '',
          mobile: '',
          meter_number: '',
          operator_name: '',
          type: '',
          invoicing_status:'',
          price_nature_id:'',
          page: 1,
          per_page: 50,
        });
      },
    });
  };

  handleEdit = () => {
    const location = this.findChildLocation();
    console.log('location', location);
    const formValues = this.EditForm.props.form.getFieldsValue();

    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `payment/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        longitude: location[0],
        latitude: location[1],
      },
      callback() {
        message.success('修改压力传感器成功');
        that.setState({
          editModal: false,
        });
        const {
          payment: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleConfig = () => {
    const formValues = this.configForm.props.form.getFieldsValue();

    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `payment/editConfig`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改压力传感器配置成功');
        that.setState({
          configModal: false,
        });
        const {
          payment: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    console.log('this.state.remark',this.state.remark)
    dispatch({
      type: `payment/remove`,
      payload: { id,remark:this.state.remark },
      callback: () => {
        message.success('撤销缴费成功');
        that.setState({
          remark:''
        })
        const {
          payment: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case 1:
        type = 'close-circle', color = '#00da4a', text = '在线';
        break;
      case -1:
        type = 'close-circle', color = '#fe1b2e', text = '离线';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };
  print = (id) => {
    request(`/print/payments/${id}`, {
      method: 'POST',
    }).then((response) => {
      if (response.status === 200) {
        if (response.data.data.account.price_nature.level === 3) {
          printUtilsLevel(response.data.data);
        } else {
          printUtils(response.data.data);
        }

      }

    });
  };
  handleExportPayment = () => {
    const {
      payment: { searchParams },
    } = this.props;
    console.log('searchParams', searchParams);
    download(`${config.prefix}/payment_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr(searchParams)}`);

  };
  Invoicing = () => {
    const state = this.InvoicingForm.state;
    const that = this
    console.log('state', state)
    if (state.step === 1) {
      message.error('请选择发票类型')
      return
    }
    this.setState({
      loading: true,
    })
    confirm({
      title: '确定要开此发票吗',
      content: '请谨慎操作',
      centered: true,
      cancelText: '取消',
      okText: '确定',
      onOk() {
        request(`/paper_invoices`, {
          method: 'POST',
          data: {
            payment_id: that.state.editRecord.id,
            buyer_name: state.mc,
            buyer_tax_number: state.nsrsbr,
            buyer_address: state.dzdh,
            buyer_bank_account: state.khh,
            invoice_push_mobile: state.sjhm,
            invoice_push_email: state.yxdz,
            invoicing_type: state.invoicing_type,
            remark: state.bz,
            remarks: [state.bz1, state.bz2],
          }
        }).then((response) => {
          if (response.status === 200) {
            message.success(`提交开"${state.mc}" 发票成功`)
            that.setState({
              loading: false,
              invoicingModal: false
            })
            const {
              payment: {searchParams},
            } = that.props;
            that.handleSearch(searchParams);
          }
          setTimeout(function () {
            that.setState({
              loading: false
            })
          }, 5000)
        });
      },
      onCancel() {
        console.log('Cancel');
        that.setState({
          loading: false,
        })
      },
    });

  }

  render() {
    const that = this;
    const {
      payment: { data, loading, tableY, meta, searchParams, selectedRowKeys, summary },
      global: { gridTableW },
    } = this.props;
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            payment: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '缴费时间',
        width: 150,
        key: 'payment_time',
        frozen: true,
      },
      {
        name: '户主姓名',
        key: 'name',
        width: 200,
        frozen: true,
        formatter: (event) => {
          return <span title={event.row.account.name}>{event.row.account.name}</span>;
        },
      },
      {
        name: '缴费金额',
        width: 100,
        key: 'amount',
        formatter: (event) => {
          return <div className={`money ${event.value < 0 ? 'error' : ''}`}><img className={'gold'} src={gold}
                                                                                 alt=""/>{event.value}</div>;
        },
      },
      {
        name: '类型',
        width: 110,
        key: 'type',
        formatter: (event) => {
          let text = '';
          switch (Number(event.value)) {
            case 1:
              text='现金';
              break;
            case 2:
              text='支票';
              break;
            case 3:
              text='银行卡';
              break;
            case 4:
              text='微信扫码';
              break;
            case 5:
              text='支付宝扫码';
              break;
            case 6:
              text='网银';
              break;
            case 30:
              text='补水';
              break;
            case 31:
              text='换表补水';
              break;
            case 11:
              return <span>公众号缴费<img style={{ width: '20px', height: '20px', marginLeft: '2px' }} src={wechat} alt=""/></span>;
            case 12:
              return <span>公众号建行<img style={{ width: '20px', height: '20px', marginLeft: '2px' }} src={wechat} alt=""/></span>;
            case 13:
              return '建行APP缴费';
            case 20:
              text = '撤销缴费';
              break;
            default:
              break;
          }
          return text;
        },
      },
      {
        name: '户主手机',
        key: 'mobile',
        width: 110,
        formatter: (event) => {
          return event.row.account.mobile;
        },
      },
      {
        name: '水表号',
        width: 130,
        key: 'meter_number',
        formatter: (event) => {
          return  <span title={event.row.account.meter_number}>{event.row.account.meter_number}</span>;
        },
      },
      {
        name: '户主地址',
        width: 170,
        key: 'address',
        formatter: (event) => {
          return <span title={event.row.account.address}>{event.row.account.address}</span>;
        },
      },
      {
        name: '用水性质',
        width: 150,
        key: 'price_nature',
        formatter: (event) => {
          return <Popover title={event.row.account.price_nature.name}
                          content={popoverPrice(event.row.account.price_nature)}>
            {event.row.account.price_nature.name}
          </Popover>;
        },
      },
      {
        name: '开票状态',
        width: 100,
        key: 'invoicing_status',
        formatter: (event) => {
          let type=''
          if(event.row.invoicing_type===1){
            type='(电子)'
          }else if(event.row.invoicing_type===2){
            type='(纸质)'
          }
          let text = '';
          switch (event.value) {
            case -3:
              text = '开票失败';
              break;
            case -2:
              text = '不允许开票';
              break;
            case -1:
              text = '未开票';
              break;
            case 1:
              text = '正在开票';
              break;
            case 2:
              text = '已开票';
              break;
          }
          return <span title={type+text}>{type+text}</span>;
        },
      },
      {
        name: '操作员',
        width: 80,
        key: 'operator_name',
      },
      {
        name: '操作',
        width: 350,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            type="primary"
            icon="printer"
            className={'btn-cyan'}
            size="small"
            onClick={(e) => {
              this.print(event.row.id);
            }
            }
          >打印
          </Button>
          <Button

            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
          {
            (event.row.status === -2 || event.row.type === 20 || event.row.type === 11 ||!find(that.permissions, { name: 'cancel_payment' })) ? null :
              <Button
                type="danger"
                size="small"
                icon="delete"
                onClick={(e) => {
                  confirm({
                    title: `确定要撤销"${event.row.account.name}" 充值金额吗?`,
                    content: <div> <p>请输入备注 : <Input defaultValue={that.state.remark} onChange={(e)=>{
                      e.persist();
                      that.setState({
                        remark:e.target.value
                      })
                    }}/>  </p> 操作不可逆，请谨慎操作！ </div>,
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered: true,
                    maskClosable: true,
                    onOk() {
                      that.handleDelete(event.row.id);
                    },
                    onCancel() {
                      console.log('Cancel');
                      that.setState({
                        remark:''
                      })
                    },
                  });
                }
                }
              >撤销
              </Button>
          }
          {
            (find(that.permissions, {name: 'paper_invoicing'}) && (event.row.invoicing_status === -1 || event.row.invoicing_status === -4 ) && event.row.type !== 20) &&
            <Button
              className={'btn-green'}
              type="primary"
              size="small"
              icon="table"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  invoicingModal: true
                })
              }}
            >开发票
            </Button>
          }
          {
            (event.row.invoicing_status === 2 && event.row.invoicing_type === 1) &&
              <Button
                type="primary"
                size="small"
                icon="table"
                onClick={(e) => {
                  request(`/invoices`, {
                    method: 'GET',
                    params:{
                      order_number: event.row.order_number
                    }
                  }).then((response) => {
                    if (response.status === 200) {
                      window.open(`${response.data.data.url}`);
                    }
                  });
                }}
              >查看发票
              </Button>
          }
         {/*  {
            (find(that.permissions, { name: 'paper_invoicing' })&& event.row.invoicing_status !== 2 && event.row.type !== 20 )&&
            <Button
              className={'btn-green'}
              type="primary"
              size="small"
              icon="table"
              onClick={(e) => {
                confirm({
                  title: `确定要开 ${event.row.account.name} 纸质发票吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    request(`/paper_invoicings`, {
                      method: 'POST',
                      data:{
                        payment_id:event.row.id
                      }
                    }).then((response) => {
                      if (response.status === 200) {
                        message.success('开纸质发票成功');
                        const {
                          payment: { searchParams },
                        } = that.props;
                        that.handleSearch(searchParams);
                      }
                    });
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });

              }}
            >开纸质发票
            </Button>
          } */}
          {
            (find(that.permissions, { name: 'paper_invoicing' })&& event.row.invoicing_type === 2)&&
            <Button
              type="danger"
              size="small"
              icon="table"
              onClick={(e) => {
                confirm({
                  title: `确定要撤销 ${event.row.account.name} 纸质发票吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    request(`/paper_invoicings/cancel`, {
                      method: 'POST',
                      data:{
                        payment_id:event.row.id
                      }
                    }).then((response) => {
                      if (response.status === 200) {
                        message.success('取消开纸质发票成功');
                        const {
                          payment: { searchParams },
                        } = that.props;
                        that.handleSearch(searchParams);
                      }
                    });
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });

              }}
            >撤销纸质发票
            </Button>
          }
        </Fragment>,
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>缴费记录</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item">
            <p>缴费总笔数 <Tooltip title={'包括补水笔数'}><Icon type="question-circle" /></Tooltip></p>
            <h4>{summary.total_count}</h4>
          </div>
          <div className="table-info-item">
            <p style={{ color: '#26b51a' }}>缴费总金额  <Tooltip title={'包括补水金额'}><Icon type="question-circle" /></Tooltip></p>
            <h4 style={{ color: '#26b51a' }}> {summary.total_amount}</h4>
          </div>
          <div size="large" className="table-info-right-item">
            <Tooltip title={'请先查询一次再导出'}>
              <Button
                className={'btn-green'}
                type="primary"
                icon="export"
                onClick={this.handleExportPayment}
              >导出缴费记录
              </Button>
            </Tooltip>
          </div>
        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                if (!String(row)) {
                  return;
                }
                this.props.dispatch({
                  type: 'payment/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          payment: { scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop = 0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`${this.state.editRecord.account && this.state.editRecord.account.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={780}
        visible={this.state.infoModal}
      >
        <Detail meter_id={this.state.editRecord.account ? this.state.editRecord.account.meter_id : ''}
                meter_number={this.state.editRecord.account ? this.state.editRecord.account.meter_number : ''}
                id={this.state.editRecord.account ? this.state.editRecord.account.id : ''}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.invoicingModal} modalClass="invoicingModal"
                                title={`开具“${this.state.editRecord.account ? this.state.editRecord.account.name : ''}” 发票`}/>}
        visible={this.state.invoicingModal}
        centered
        destroyOnClose
        onOk={() => {
          this.Invoicing()
        }}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        className="invoicingModal"
        width={1100}
        onCancel={() => {
          this.setState({invoicingModal: false});
        }}

      >
        <PaperInvoicing editRecord={this.state.editRecord} wrappedComponentRef={(inst) => this.InvoicingForm = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
